<template>
  <div class="chat-container">
    <div class="chat-wrapper">
      <div class="chat-sidebar">
        <div class="history-header">
          <h3>历史对话</h3>
          <button class="new-chat-btn" @click="startNewChat">
            <span>+</span> 新对话
          </button>
        </div>
        <div class="history-list">
          <div v-if="chatHistory.length === 0" class="empty-history">
            暂无历史对话
          </div>
          <div 
            v-for="(chat, index) in chatHistory" 
            :key="index" 
            :class="['history-item', { active: currentChatIndex === index && !isNewChat() }]"
            @click="loadChat(index)"
          >
            <div class="history-title">
              <!-- 没有ID的是新对话，显示特殊样式 -->
              <span v-if="!chat.id" class="new-chat-label">新对话</span>
              <span v-else>{{ chat.title }}</span>
            </div>
            <div class="history-info">
              <span class="history-date">{{ chat.date }}</span>
              <span class="history-msg-count">{{ chat.messages && chat.messages.length > 0 ? chat.messages.length : (chat.messageCount || 0) }}条消息</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-main">
        <div class="chat-header">
          <h2>音乐助手</h2>
        </div>
        
        <div class="messages">
          <div v-for="(message, index) in currentChat.messages" :key="message.key || index" 
               :class="['message', message.type]">
            <div class="message-content" v-if="message.type === 'sent'">{{ message.text }}</div>
            <div class="message-content markdown-body" v-else v-html="renderMarkdown(message.text)"></div>
            <div class="message-time">{{ message.time }}</div>
          </div>
          
          <!-- 正在输入指示器 -->
          <div v-if="typingIndicator" class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
        
        <div class="input-area">
          <input 
            type="text" 
            v-model="newMessage" 
            @keyup.enter="sendMessage"
            placeholder="输入您的问题..." 
            class="message-input" 
          />
          <button class="send-button" @click="sendMessage">发送</button>
        </div>
      </div>
    </div>
    
    <!-- 快速帮助按钮 -->
    <button v-if="!showGuide" class="help-button" @click="restartGuide" title="查看使用引导">
      <i class="fas fa-question-circle"></i>
    </button>
    
    <!-- 引导功能 -->
    <teleport to="body">
      <div v-if="showGuide" class="guide-overlay">
        <div class="guide-container" :class="`guide-step-${guideStep}`">
          <div class="guide-header">
            <h3>音乐助手使用引导 <span>{{ guideStep }}/{{ totalGuideSteps }}</span></h3>
            <button class="guide-close" @click="closeGuide">&times;</button>
          </div>
          
          <div class="guide-content">
            <div v-if="guideStep === 1" class="guide-step">
              <div class="guide-icon"><i class="fas fa-comments"></i></div>
              <h4>第一步：创建新对话</h4>
              <p>点击左侧"新对话"按钮开始与音乐助手交流。每个新对话都会被保存，方便您随时回顾。</p>
            </div>
            
            <div v-if="guideStep === 2" class="guide-step">
              <div class="guide-icon"><i class="fas fa-keyboard"></i></div>
              <h4>第二步：提问音乐问题</h4>
              <p>在底部输入框中输入您的音乐相关问题，例如乐理知识、乐器演奏技巧、音乐历史等，按Enter或点击发送按钮。</p>
            </div>
            
            <div v-if="guideStep === 3" class="guide-step">
              <div class="guide-icon"><i class="fas fa-music"></i></div>
              <h4>第三步：获取专业回答</h4>
              <p>音乐助手会利用专业知识回答您的问题，支持Markdown和LaTeX数学公式，能清晰展示音乐符号和概念。</p>
            </div>
            
            <div v-if="guideStep === 4" class="guide-step">
              <div class="guide-icon"><i class="fas fa-history"></i></div>
              <h4>第四步：管理历史对话</h4>
              <p>左侧边栏显示您的所有历史对话，点击即可切换不同的对话，助手会记住上下文，便于持续学习。</p>
            </div>
          </div>
          
          <div class="guide-footer">
            <button v-if="guideStep > 1" class="btn secondary" @click="prevGuideStep">上一步</button>
            <button v-if="guideStep < totalGuideSteps" class="btn primary" @click="nextGuideStep">下一步</button>
            <button v-if="guideStep === totalGuideSteps" class="btn primary" @click="closeGuide">开始使用</button>
          </div>
        </div>
      </div>
    </teleport>
  </div>
</template>

<script>
import axios from 'axios';
import DOMPurify from 'dompurify';
import 'github-markdown-css/github-markdown.css';
import 'katex/dist/katex.min.css';
import MarkdownIt from 'markdown-it';
import markdownItKatex from 'markdown-it-katex';

export default {
  name: 'ChatView',
  props: {
    id: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      newMessage: '',
      currentChatIndex: 0,
      chatHistory: [], // 初始设为空数组，不包含任何本地预设对话
      typingIndicator: false,
      animationsEnabled: true,
      // 引导功能数据
      showGuide: false,
      guideStep: 1,
      totalGuideSteps: 4,
      guideFirstVisit: true,
      // 流式响应数据
      currentStreamResponse: '',
      // 初始化MarkdownIt实例
      md: null,
      // 主题设置，保留此变量用于与全局主题同步
      isDarkTheme: false,
      // 用于中断流式请求
      abortController: null,
      // 用于追踪会话ID（URL中和当前活跃的）
      currentConversationId: null,
      // 前端存储中间状态用，不与服务端状态同步
      activeConversationId: null,
      // 当前的EventSource实例
      eventSource: null,
      // 自动重连尝试次数
      reconnectAttempts: 0,
      // 最大重连尝试次数
      maxReconnectAttempts: 3,
      // 用于防止重复加载消息
      isLoadingMessages: false,
      // 用于防止重复获取历史
      isFetchingHistory: false,
      // 用户认证token
      authToken: null,
      // 是否正在初始化
      isInitializing: true,
      // 最后获取历史记录的时间戳
      lastHistoryFetch: null
    }
  },
  computed: {
    // 只读映射，无副作用
    currentChat() {
      // 空历史或越界时返回新对话
      if (this.chatHistory.length === 0 || 
          this.currentChatIndex < 0 || 
          this.currentChatIndex >= this.chatHistory.length) {
        return {
          id: null,
          title: '新对话',
          date: this.formatDate(new Date()),
          messages: []
        };
      }
      
      // 返回历史记录中的当前聊天
      return this.chatHistory[this.currentChatIndex];
    },
    
    // 获取认证头
    authHeaders() {
      return this.authToken ? {
        'Authorization': `Bearer ${this.authToken}`
      } : {};
    },
    
    // API基础URL
    apiBaseUrl() {
      return 'http://localhost:8000';
    }
  },
  created() {
    // 初始化MarkdownIt实例
    this.md = new MarkdownIt({
      html: true,
      breaks: true,
      linkify: true
    });
    this.md.use(markdownItKatex);
    
    // 从localStorage中获取主题设置
    const savedTheme = localStorage.getItem('chatTheme');
    this.isDarkTheme = savedTheme === 'dark';
    this.applyTheme();
    
    // 从localStorage获取token
    const userInfo = localStorage.getItem('user');
    if (userInfo) {
      try {
        const user = JSON.parse(userInfo);
        if (user && user.access_token) {
          this.authToken = user.access_token;
        } else if (user && user.token) {
          this.authToken = user.token;
        }
      } catch (e) {
        console.error('解析用户信息失败:', e);
      }
    }
    
    // 监听主题变化事件
    window.addEventListener('themeChange', this.handleThemeChange);
  },
  mounted() {
    // 加载动画
    this.initAnimations();
    
    // 如果没有token，重定向到登录页
    if (!this.authToken) {
      this.$router.push('/login');
      return;
    }
    
    // 根据URL ID加载特定对话或加载历史
    this.initializeChat();
    
    // 滚动到最新消息
    this.$nextTick(() => {
      this.scrollToBottom(true);
    });
    
    // 检查用户是否是第一次访问
    const hasVisitedChat = localStorage.getItem('hasVisitedChat');
    if (!hasVisitedChat) {
      // 显示引导
      this.showGuide = true;
      // 记录已访问
      localStorage.setItem('hasVisitedChat', 'true');
    }
    
    // 添加键盘快捷键支持
    document.addEventListener('keydown', this.handleKeydown);
    
    // 添加页面可见性变化监听
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
    
    // 监听页面加载完成事件，用于页面刷新后的重连
    window.addEventListener('load', this.handlePageLoad);
    
    // 监听路由变化
    this.$watch('$route', this.handleRouteChange);
  },
  
  beforeUnmount() {
    // 移除事件监听器
    document.removeEventListener('keydown', this.handleKeydown);
    window.removeEventListener('themeChange', this.handleThemeChange);
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
    window.removeEventListener('load', this.handlePageLoad);
    
    // 组件销毁前确保所有流式请求都被中断
    this.closeEventSource();
  },
  methods: {
    // 判断当前是否是新对话 - 基于路由
    isNewChat() {
      // 如果路由是/chat/c（没有ID），则是新对话
      // 如果路由是/chat/c/xxx（有ID），则是现有对话
      return this.$route.name === 'ChatHome' || !this.$route.params.id;
    },
    
    // 处理来自导航栏的主题变化
    handleThemeChange(e) {
      this.isDarkTheme = e.detail.isDark;
      this.applyTheme();
    },
    
    // 应用主题样式
    applyTheme() {
      // 在白天模式下移除黑暗模式的所有样式
      document.body.classList.remove('dark-theme');
      
      // 只有在需要黑暗模式时才添加相应类
      if (this.isDarkTheme) {
        document.body.classList.add('dark-theme');
      }
    },
    
    renderMarkdown(text) {
      if (!text) return '';
      
      try {
        // 使用markdown-it渲染Markdown和LaTeX
        const html = this.md.render(String(text));
        
        // 净化HTML
        return DOMPurify.sanitize(html, {
          ADD_TAGS: ['math', 'mrow', 'msup', 'mi', 'mn', 'mo', 'mfrac', 'msqrt'],
          ADD_ATTR: ['class', 'style']
        });
      } catch (e) {
        console.error('Markdown渲染错误:', e);
        return text;
      }
    },
    
    initAnimations() {
      // 初始化侧边栏动画
      const sidebar = document.querySelector('.chat-sidebar');
      if (sidebar) {
        sidebar.style.opacity = '0';
        sidebar.style.transform = 'translateX(-20px)';
        
        setTimeout(() => {
          sidebar.style.transition = 'all 0.5s cubic-bezier(0.23, 1, 0.32, 1)';
          sidebar.style.opacity = '1';
          sidebar.style.transform = 'translateX(0)';
        }, 100);
      }
      
      // 初始化历史记录条目动画
      const historyItems = document.querySelectorAll('.history-item');
      historyItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateY(10px)';
        
        setTimeout(() => {
          item.style.transition = 'all 0.3s cubic-bezier(0.23, 1, 0.32, 1)';
          item.style.opacity = '1';
          item.style.transform = 'translateY(0)';
        }, 200 + index * 50);
      });
      
      // 初始化消息动画
      const messages = document.querySelectorAll('.message');
      messages.forEach((message, index) => {
        message.style.opacity = '0';
        message.style.transform = message.classList.contains('sent') ? 
          'translateX(20px)' : 'translateX(-20px)';
        
        setTimeout(() => {
          message.style.transition = 'all 0.4s cubic-bezier(0.23, 1, 0.32, 1)';
          message.style.opacity = '1';
          message.style.transform = 'translateX(0)';
        }, 300 + index * 100);
      });
    },
    
    // 初始化聊天，根据URL决定加载哪个对话
    async initializeChat() {
      this.isInitializing = true;
      
      // 检查是否需要加载历史记录
      const needFetchHistory = this.chatHistory.length === 0 || (Date.now() - (this.lastHistoryFetch || 0) > 300000); // 5分钟更新一次
      
      if (needFetchHistory) {
        // 记录最后获取时间
        this.lastHistoryFetch = Date.now();
        // 加载历史
        await this.fetchChatHistory();
      }
      
      // 检查URL中是否有会话ID
      const conversationId = this.id ? parseInt(this.id) : null;
      
      if (conversationId) {
        // 如果URL中有ID，尝试加载该对话
        this.loadSpecificConversation(conversationId);
        console.log("根据URL加载特定对话，ID:", conversationId);
      } else if (this.chatHistory.length > 0) {
        // 默认加载第一个对话
        this.currentChatIndex = 0;
        this.updateUrlWithCurrentChat();
        console.log("加载第一个历史对话");
      } else {
        // 没有历史，创建新对话
        this.startNewChat();
        console.log("没有历史记录，创建新对话");
      }
      
      this.isInitializing = false;
    },
    
    // 加载指定ID的对话
    loadSpecificConversation(conversationId) {
      // 查找对话在历史中的索引
      const index = this.chatHistory.findIndex(chat => chat.id === conversationId);
      
      if (index !== -1) {
        // 如果在历史中找到，直接切换
        this.currentChatIndex = index;
        this.currentConversationId = conversationId;
        
        // 如果消息为空但存在消息计数大于0，才加载消息内容
        const selectedChat = this.chatHistory[index];
        if ((!selectedChat.messages || selectedChat.messages.length === 0) && 
            selectedChat.messageCount > 0) {
          this.loadChatMessages(conversationId, index);
        }
        
        // 不需要更新URL，因为是从URL变化触发的加载
      } else {
        // 如果不在历史中，通过API加载
        this.loadConversationById(conversationId);
      }
    },
    
    // 处理路由变化
    handleRouteChange(to, from) {
      // 如果是初始化阶段，忽略路由变化
      if (this.isInitializing) return;
      
      const newId = to.params.id ? parseInt(to.params.id) : null;
      const oldId = from.params.id ? parseInt(from.params.id) : null;
      
      // 如果ID发生变化
      if (newId !== oldId) {
        console.log(`路由变化: 从 ${oldId || 'null'} 到 ${newId || 'null'}`);
        
        // 从有ID变为无ID，应是创建新对话
        if (oldId !== null && newId === null) {
          console.log("URL从有ID变为无ID，创建新对话");
          this.startNewChat();
          return;
        }
        
        // 防止重复加载
        if (newId === this.currentConversationId) {
          console.log('当前已是目标会话，无需重新加载');
          return;
        }
        
        if (newId) {
          // 只加载指定ID的对话，不重新获取整个历史记录
          this.loadSpecificConversation(newId);
        } else {
          // 没有ID但有历史记录，显示第一个对话或创建新对话
          if (this.chatHistory.length > 0) {
            this.currentChatIndex = 0;
            // 不更新URL，避免循环
          } else {
            this.startNewChat();
          }
        }
      }
    },
    
    // 更新URL以反映当前对话
    updateUrlWithCurrentChat(reloadEntirePage = false) {
      if (!this.currentChat || this.isInitializing) return;
      
      const currentId = this.currentChat.id;
      if (currentId) {
        // 更新URL但不重新加载页面
        this.$router.push({
          name: 'ChatConversation',
          params: { id: currentId.toString() },
          // 添加replace选项，使用replace而非push以避免导航历史堆积
          replace: !reloadEntirePage
        }).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            throw err;
          }
        });
        
        this.currentConversationId = currentId;
      } else {
        // 如果是新对话且没有ID，使用基础URL
        this.$router.push({ 
          name: 'ChatHome',
          // 添加replace选项，使用replace而非push以避免导航历史堆积
          replace: !reloadEntirePage
        }).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            throw err;
          }
        });
      }
    },
    
    // 获取聊天历史
    async fetchChatHistory() {
      // 防止重复获取，避免递归
      if (this.isFetchingHistory) return;
      this.isFetchingHistory = true;
      
      try {
        const response = await axios.get(
          `${this.apiBaseUrl}/chat/history`, 
          { headers: this.authHeaders }
        );
        
        if (response.data.success && response.data.conversations && response.data.conversations.length > 0) {
          // 转换服务器返回的会话数据
          const serverConversations = response.data.conversations.map(conv => {
            let chatDate;
            if (conv.created_at) {
              chatDate = this.formatDate(new Date(conv.created_at));
            } else {
              chatDate = this.formatDate(new Date());
            }
            
            // 获取消息数量，后端返回的消息数量或默认为0
            const messageCount = conv.message_count || 0;
            
            return {
              id: conv.id,
              title: conv.title || (conv.first_message ? (conv.first_message.substring(0, 15) + (conv.first_message.length > 15 ? '...' : '')) : '新对话'),
              date: chatDate,
              messages: [],
              messageCount: messageCount // 添加消息计数字段
            };
          });
          
          let finalChatHistory = [];
          
          // 保留已加载消息内容的对话
          if (this.chatHistory.length > 0) {
            // 合并现有的消息内容到新的会话列表
            finalChatHistory = serverConversations.map(newConv => {
              // 查找当前历史中是否已有该会话
              const existingConv = this.chatHistory.find(oldConv => oldConv.id === newConv.id);
              // 如果找到且有消息，保留消息内容
              if (existingConv && existingConv.messages && existingConv.messages.length > 0) {
                return {
                  ...newConv,
                  messages: existingConv.messages
                };
              }
              return newConv;
            });
          } else {
            // 如果是第一次加载，直接使用服务器数据
            finalChatHistory = serverConversations;
          }
          
          // 更新历史记录
          this.chatHistory = finalChatHistory;
          
          // 安全设置索引
          if (this.chatHistory.length > 0) {
            // 检查当前会话ID是否在新的历史记录中
            if (this.currentConversationId) {
              const index = this.chatHistory.findIndex(chat => chat.id === this.currentConversationId);
              if (index !== -1) {
                this.currentChatIndex = index;
              } else {
                this.currentChatIndex = 0;
              }
            } else {
              this.currentChatIndex = 0;
            }
          } else {
            this.currentChatIndex = 0;
            this.startNewChat();
          }
        } else {
          this.chatHistory = [];
          this.startNewChat();
        }
      } catch (error) {
        console.error('加载聊天历史失败:', error);
        this.chatHistory = [];
        this.startNewChat();
      } finally {
        this.isFetchingHistory = false;
      }
    },
    
    // 通过API加载特定ID的对话
    async loadConversationById(conversationId) {
      try {
        const response = await axios.get(
          `${this.apiBaseUrl}/chat/messages/${conversationId}`, 
          { headers: this.authHeaders }
        );
        
        if (response.data.success) {
          // 创建对话对象
          const conversation = response.data.conversation;
          const messages = response.data.messages;
          
          const formattedMessages = messages.map(msg => ({
            type: msg.role === 'user' ? 'sent' : 'received',
            text: msg.content,
            time: msg.created_at ? this.formatTime(new Date(msg.created_at)) : this.getCurrentTime(),
            key: `msg-${msg.id || Date.now()}-${Math.random().toString(36).substr(2, 9)}`
          }));
          
          const chatObj = {
            id: conversation.id,
            title: conversation.title || '对话',
            date: conversation.created_at ? this.formatDate(new Date(conversation.created_at)) : this.formatDate(new Date()),
            messages: formattedMessages,
            messageCount: formattedMessages.length
          };
          
          // 添加到历史中
          this.chatHistory = [chatObj, ...this.chatHistory.filter(c => c.id !== conversationId)];
          this.currentChatIndex = 0;
          this.currentConversationId = conversationId;
          
          // 不需要更新URL，因为是从URL变化触发的加载
        } else {
          // 加载失败，创建新对话
          console.error('加载对话失败:', response.data.message);
          this.startNewChat();
        }
      } catch (error) {
        console.error('加载对话失败:', error);
        this.startNewChat();
      }
    },
    
    // 加载聊天消息
    loadChatMessages(conversationId, index) {
      // 防止重复加载，避免递归
      if (this.isLoadingMessages) return;
      this.isLoadingMessages = true;
      
      // 检查索引是否有效
      if (index < 0 || index >= this.chatHistory.length) {
        this.isLoadingMessages = false;
        return;
      }
      
      axios.get(
        `${this.apiBaseUrl}/chat/messages/${conversationId}`, 
        { headers: this.authHeaders }
      )
        .then(response => {
          if (response.data.success && response.data.messages) {
            // 再次检查索引是否仍然有效
            if (index < 0 || index >= this.chatHistory.length) {
              return;
            }
            
            // 转换消息格式
            const messages = response.data.messages.map(msg => {
              let messageTime;
              if (msg.created_at) {
                messageTime = this.formatTime(new Date(msg.created_at));
              } else {
                messageTime = this.getCurrentTime();
              }
              return {
                type: msg.role === 'user' ? 'sent' : 'received',
                text: msg.content,
                time: messageTime,
                key: `msg-${msg.id || Date.now()}-${Math.random().toString(36).substr(2, 9)}`
              };
            });
            
            // 创建新的聊天历史副本
            const newChatHistory = [...this.chatHistory];
            // 创建新的聊天对象，而不是修改现有对象
            newChatHistory[index] = {
              ...newChatHistory[index],
              messages,
              messageCount: messages.length // 更新消息计数
            };
            // 一次性替换整个历史记录
            this.chatHistory = newChatHistory;
            
            // 修正索引，确保不越界
            if (this.currentChatIndex >= this.chatHistory.length) {
              this.currentChatIndex = this.chatHistory.length - 1;
            }
            if (this.currentChatIndex < 0 && this.chatHistory.length > 0) {
              this.currentChatIndex = 0;
            }
            
            // 消息加载完成后，强制滚动到底部
            this.$nextTick(() => {
              this.scrollToBottom(true);
            });
          }
        })
        .catch(error => {
          console.error('加载对话消息失败:', error);
        })
        .finally(() => {
          this.isLoadingMessages = false;
        });
    },
    
    startNewChat() {
      // 立即关闭所有连接
      this.closeEventSource();

      // 强制清除所有ID和状态变量
      this.currentConversationId = null;
      this.activeConversationId = null;
      
      // 创建新对话并切换
      const newChat = {
        id: null,
        title: '新对话',
        date: this.formatDate(new Date()),
        messages: [],
        messageCount: 0
      };
      
      // 完全替换历史记录数组，确保响应式更新
      const updatedHistory = [newChat, ...this.chatHistory];
      this.chatHistory = updatedHistory;
      this.currentChatIndex = 0;
      
      console.log("创建新对话，重置所有会话状态");
      
      // 立即更新URL到/chat/c - 这将标识为新对话
      console.log("立即更新URL到/chat/c基础路径，这将标识为新对话");
      this.$router.push({ 
        name: 'ChatHome',
        replace: true
      }).catch(err => {
        if (err.name !== 'NavigationDuplicated') {
          throw err;
        }
      });
      
      // 添加新聊天的动画效果
      this.$nextTick(() => {
        const firstItem = document.querySelector('.history-item');
        if (firstItem) {
          firstItem.style.opacity = '0';
          firstItem.style.transform = 'scale(0.95)';
          
          setTimeout(() => {
            firstItem.style.transition = 'all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)';
            firstItem.style.opacity = '1';
            firstItem.style.transform = 'scale(1)';
          }, 10);
        }
      });
    },
    
    loadChat(index) {
      if (index < 0 || index >= this.chatHistory.length) return;
      
      // 关闭当前可能的连接
      this.closeEventSource();
      
      // 先设置索引，无论是否是当前聊天
      this.currentChatIndex = index;
          
      // 获取选中的聊天
      const selectedChat = this.chatHistory[index];
      
      // 保存会话ID
      this.currentConversationId = selectedChat.id;
      console.log(`加载对话 ${index}, ID: ${selectedChat.id || 'null'}`);
      
      // 更新URL，但不要触发整页刷新
      if (selectedChat.id) {
        // 使用带ID的路由 - 这会标识为现有对话
        console.log("更新为带ID的路由，标识为现有对话");
        this.$router.push({
          name: 'ChatConversation',
          params: { id: selectedChat.id.toString() },
          replace: true
        }).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            throw err;
          }
        });
      } else {
        // 如果是无ID的新对话，使用基础路由 - 这会标识为新对话
        console.log("更新为基础路由，标识为新对话");
        this.$router.push({
          name: 'ChatHome',
          replace: true
        }).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            throw err;
          }
        });
      }
      
      // 如果有ID但没有消息，且有消息计数大于0，才加载消息内容
      if (selectedChat.id && 
          (!selectedChat.messages || selectedChat.messages.length === 0) && 
          selectedChat.messageCount > 0) {
        this.loadChatMessages(selectedChat.id, index);
      }
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom(true);
      });
    },
    
    sendMessage() {
      if (!this.newMessage.trim()) return;
      
      const messageText = this.newMessage;
      this.newMessage = '';
      
      // 添加用户消息，带动画
      this.addMessage('sent', messageText);
      
      // 检查是否是新会话的第一条消息 - 使用路由判断
      const isFirstMessage = this.isNewChat();
      
      // 如果是第一条用户消息，使用前几个字作为对话标题
      if (isFirstMessage) {
        const newTitle = messageText.substring(0, 15) + (messageText.length > 15 ? '...' : '');
        
        // 创建深拷贝以更新标题
        const chatIndex = this.currentChatIndex;
        const newChatHistory = [...this.chatHistory];
        const updatedChat = JSON.parse(JSON.stringify(newChatHistory[chatIndex]));
        updatedChat.title = newTitle;
        newChatHistory[chatIndex] = updatedChat;
        this.chatHistory = newChatHistory;
        
        console.log("第一条消息已发送，当前路由:", this.$route.path);
      }
      
      // 检查认证token
      if (!this.authToken) {
        this.typingIndicator = false;
        this.addMessage('received', '请先登录后再使用聊天功能');
        return;
      }
      
      // 显示正在输入指示器
      this.typingIndicator = true;
      
      // 调用流式API
      this.callStreamApi(messageText);
    },
    
    addMessage(type, text) {
      // 防止越界，避免递归
      if (!this.currentChat || !this.currentChat.messages || 
          this.currentChatIndex < 0 || this.currentChatIndex >= this.chatHistory.length) {
        return;
      }
      
      // 创建一个新的消息对象
      const newMessage = {
        type,
        text,
        time: this.getCurrentTime(),
        key: `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      };
      
      // 找到当前聊天在历史中的索引
      const chatIndex = this.currentChatIndex;
      
      // 深拷贝当前整个聊天对象
      const updatedChat = JSON.parse(JSON.stringify(this.chatHistory[chatIndex]));
      
      // 添加新消息
      updatedChat.messages.push(newMessage);
      
      // 更新消息计数
      updatedChat.messageCount = updatedChat.messages.length;
      
      // 创建整个聊天历史的副本
      const newChatHistory = [...this.chatHistory];
      
      // 替换当前聊天
      newChatHistory[chatIndex] = updatedChat;
      
      // 完全替换聊天历史
      this.chatHistory = newChatHistory;
      
      // 修正索引，确保不越界
      if (this.currentChatIndex >= this.chatHistory.length) {
        this.currentChatIndex = this.chatHistory.length - 1;
      }
      if (this.currentChatIndex < 0 && this.chatHistory.length > 0) {
        this.currentChatIndex = 0;
      }
      
      // 消息添加后，滚动到底部
      this.scrollToBottom(true);
    },
    
    scrollToBottom(force = false) {
      this.$nextTick(() => {
        const messagesContainer = document.querySelector('.messages');
        if (messagesContainer) {
          // 检查是否需要滚动
          const isNearBottom = force || 
            (messagesContainer.scrollHeight - messagesContainer.scrollTop - messagesContainer.clientHeight < 200);
          
          if (isNearBottom) {
            // 使用requestAnimationFrame确保DOM已完全渲染
            window.requestAnimationFrame(() => {
              messagesContainer.scrollTop = messagesContainer.scrollHeight;
              
              // 双重保险：再次延迟滚动以应对一些渲染延迟的情况
              setTimeout(() => {
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
              }, 50);
            });
          }
        }
      });
    },
    
    getCurrentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 处理键盘快捷键
    handleKeydown(event) {
      // ESC键关闭引导
      if (event.key === 'Escape' && this.showGuide) {
        this.closeGuide();
      }
    },
    
    // 处理页面完全加载事件
    handlePageLoad() {
      console.log("页面加载完成，通过路由处理");
      
      // 防止重复处理
      if (this.handlingPageEvent) return;
      this.handlingPageEvent = true;
      
      try {
        // 页面已通过路由处理
        this.handlingPageEvent = false;
      } catch (e) {
        console.error("处理页面加载事件出错:", e);
        this.handlingPageEvent = false;
      }
    },
    
    // 处理页面可见性变化
    handleVisibilityChange() {
      // 防止重复处理
      if (this.handlingVisibilityEvent) return;
      this.handlingVisibilityEvent = true;
      
      try {
        // 如果页面重新变为可见
        if (!document.hidden) {
          console.log("页面重新可见，检查是否需要刷新数据");
          
          // 如果已登录且有会话ID，可以考虑刷新数据
          if (this.authToken && this.currentConversationId) {
            // 在这里可以添加刷新数据的逻辑
          }
        }
      } catch (e) {
        console.error("处理页面可见性变化事件出错:", e);
      }
      
      this.handlingVisibilityEvent = false;
    },
    
    // 引导功能方法
    nextGuideStep() {
      if (this.guideStep < this.totalGuideSteps) {
        this.guideStep++;
        this.highlightCurrentStep();
      } else {
        this.closeGuide();
      }
    },
    
    prevGuideStep() {
      if (this.guideStep > 1) {
        this.guideStep--;
        this.highlightCurrentStep();
      }
    },
    
    closeGuide() {
      this.showGuide = false;
      this.guideStep = 1;
      // 移除所有高亮效果
      this.removeAllHighlights();
    },
    
    restartGuide() {
      this.showGuide = true;
      this.guideStep = 1;
      this.highlightCurrentStep();
    },
    
    // 高亮当前步骤对应的UI元素
    highlightCurrentStep() {
      // 首先移除所有高亮
      this.removeAllHighlights();
      
      // 根据当前步骤添加高亮
      switch(this.guideStep) {
        case 1:
          // 高亮新对话按钮和侧边栏
          this.addHighlight('.history-header .new-chat-btn', 'highlight-sidebar');
          break;
        case 2:
          // 高亮输入区域
          this.addHighlight('.input-area', 'highlight-input');
          break;
        case 3:
          // 高亮聊天区域
          this.addHighlight('.messages', 'highlight-chat');
          break;
        case 4:
          // 高亮历史列表
          this.addHighlight('.history-list', 'highlight-history');
          break;
      }
    },
    
    // 添加高亮效果
    addHighlight(selector, className) {
      const element = document.querySelector(selector);
      if (element) {
        element.classList.add(className);
        
        // 如果元素不在视口内，滚动到该元素
        const rect = element.getBoundingClientRect();
        if (
          rect.bottom < 0 || 
          rect.top > window.innerHeight ||
          rect.right < 0 || 
          rect.left > window.innerWidth
        ) {
          element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }
    },
    
    // 移除所有高亮效果
    removeAllHighlights() {
      const highlights = ['highlight-sidebar', 'highlight-input', 'highlight-chat', 'highlight-history'];
      highlights.forEach(className => {
        const elements = document.querySelectorAll(`.${className}`);
        elements.forEach(el => el.classList.remove(className));
      });
    },
    
    // 关闭EventSource连接
    closeEventSource() {
      if (this.eventSource) {
        try {
          this.eventSource.close();
          console.log('EventSource连接已关闭');
        } catch (e) {
          console.error('关闭EventSource时出错:', e);
        }
        this.eventSource = null;
      }
    },
    
    // 添加空的接收消息
    addEmptyReceivedMessage() {
      // 防止越界和递归
      if (!this.currentChat || !this.currentChat.messages || 
          this.currentChatIndex < 0 || this.currentChatIndex >= this.chatHistory.length) {
        return;
      }
      
      const newMessage = {
        type: 'received',
        text: '',
        time: this.getCurrentTime(),
        key: `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      };
      
      // 创建一个新的消息数组，并添加新消息
      const chatIndex = this.currentChatIndex;
      const newChatHistory = [...this.chatHistory];
      
      // 再次检查索引是否有效
      if (chatIndex < 0 || chatIndex >= newChatHistory.length) {
        return;
      }
      
      const updatedChat = JSON.parse(JSON.stringify(newChatHistory[chatIndex]));
      updatedChat.messages.push(newMessage);
      newChatHistory[chatIndex] = updatedChat;
      
      // 一次性替换整个聊天历史
      this.chatHistory = newChatHistory;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom(true);
      });
    },
    
    // 添加错误消息
    addErrorMessage(errorText) {
      // 防止越界和递归
      if (!this.currentChat || !this.currentChat.messages || 
          this.currentChatIndex < 0 || this.currentChatIndex >= this.chatHistory.length) {
        return;
      }
      
      const newMessage = {
        type: 'received',
        text: `⚠️ ${errorText}`,
        time: this.getCurrentTime(),
        key: `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      };
      
      // 创建一个新的消息数组，并添加新消息
      const chatIndex = this.currentChatIndex;
      const newChatHistory = [...this.chatHistory];
      
      // 再次检查索引是否有效
      if (chatIndex < 0 || chatIndex >= newChatHistory.length) {
        return;
      }
      
      const updatedChat = JSON.parse(JSON.stringify(newChatHistory[chatIndex]));
      updatedChat.messages.push(newMessage);
      newChatHistory[chatIndex] = updatedChat;
      
      // 一次性替换整个聊天历史
      this.chatHistory = newChatHistory;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom(true);
      });
    },
    
    // 更新最后一条消息并重新渲染
    updateLastMessage(text) {
      // 防止递归和越界
      if (!this.currentChat || !this.currentChat.messages || this.currentChat.messages.length === 0 ||
          this.currentChatIndex < 0 || this.currentChatIndex >= this.chatHistory.length) {
        return;
      }
      
      const lastIndex = this.currentChat.messages.length - 1;
      const currentMessage = this.currentChat.messages[lastIndex];
      
      // 检查消息是否有变化
      if (currentMessage.text === text) {
        return; // 如果内容没变，直接返回避免不必要的更新
      }
      
      // 生成唯一key强制重新渲染
      const uniqueKey = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      
      // 创建新的聊天历史副本
      const chatIndex = this.currentChatIndex;
      const newChatHistory = [...this.chatHistory];
      
      // 再次检查索引是否有效
      if (chatIndex < 0 || chatIndex >= newChatHistory.length) {
        return;
      }
      
      // 创建当前聊天对象的深拷贝
      const updatedChat = JSON.parse(JSON.stringify(newChatHistory[chatIndex]));
      
      // 更新最后一条消息
      if (updatedChat.messages.length > 0) {
        updatedChat.messages[updatedChat.messages.length - 1] = {
          ...updatedChat.messages[updatedChat.messages.length - 1],
          text: text,
          key: uniqueKey
        };
      }
      
      // 更新聊天历史
      newChatHistory[chatIndex] = updatedChat;
      this.chatHistory = newChatHistory;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom(true);
      });
    },
    
    // 在流式输出完成时，将最终文本更新到响应式系统
    finalizeMessageUpdate(text) {
      // 防止越界、空数据和递归
      if (!this.currentChat || !this.currentChat.messages || this.currentChat.messages.length === 0 ||
          this.currentChatIndex < 0 || this.currentChatIndex >= this.chatHistory.length) {
        return;
      }
      
      const lastIndex = this.currentChat.messages.length - 1;
      const currentMessage = this.currentChat.messages[lastIndex];
      
      // 检查消息是否有变化，无变化则不更新避免递归
      if (currentMessage.text === text) {
        return;
      }
      
      // 生成唯一key强制重新渲染
      const uniqueKey = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      
      // 深拷贝当前整个聊天历史
      const chatIndex = this.currentChatIndex;
      const newChatHistory = [...this.chatHistory];
      
      // 再次检查索引是否有效
      if (chatIndex < 0 || chatIndex >= newChatHistory.length) {
        return;
      }
      
      // 创建当前聊天对象的深拷贝
      const updatedChat = JSON.parse(JSON.stringify(newChatHistory[chatIndex]));
      
      // 更新最后一条消息
      if (updatedChat.messages.length > 0) {
        updatedChat.messages[updatedChat.messages.length - 1] = {
          ...updatedChat.messages[updatedChat.messages.length - 1],
          text: text,
          key: uniqueKey
        };
      }
      
      // 更新聊天历史
      newChatHistory[chatIndex] = updatedChat;
      this.chatHistory = newChatHistory;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom(true);
      });
    },
    
    // 直接更新DOM以避免过多的Vue响应式更新
    updateMessageDOM(text) {
      const messagesContainer = document.querySelector('.messages');
      if (!messagesContainer) return;
      
      const lastMessage = messagesContainer.querySelector('.message.received:last-child .message-content');
      if (lastMessage) {
        // 渲染Markdown并更新内容
        lastMessage.innerHTML = this.renderMarkdown(text);
        // 滚动到底部
        this.scrollToBottom(true);
      }
    },
    
    // 调用流式API
    callStreamApi(messageText) {
      // 设置全局刷新标志，用于抑制刷新时的错误显示
      window.isRefreshing = false;

      // 关闭任何现有的EventSource连接
      this.closeEventSource();
      
      // 通过路由判断是否是新对话
      const isNewChatRoute = this.isNewChat();
      
      // 详细诊断信息
      console.log("准备发送消息，路由状态:", {
        "currentRoute": this.$route.path,
        "isNewChat(路由判断)": isNewChatRoute,
        "currentChatID": this.currentChat.id
      });
      
      // 确定API URL - 使用路由判断
      let url;
      
      if (isNewChatRoute) {
        // 新对话：使用基础URL创建新会话
        console.log("确认是新对话(路由=/chat/c)，使用基础API创建新会话");
        url = `${this.apiBaseUrl}/chat/stream?message=${encodeURIComponent(messageText)}`;
        
        // 清除所有ID
        this.currentConversationId = null;
      } else {
        // 现有对话：使用带ID的URL
        const routeId = this.$route.params.id;
        console.log(`使用路由ID: ${routeId}`);
        url = `${this.apiBaseUrl}/chat/stream/${routeId}?message=${encodeURIComponent(messageText)}`;
      }
      
      // 添加token作为查询参数
      if (this.authToken) {
        url += `&token=${encodeURIComponent(this.authToken)}`;
        console.log("添加token到URL");
      } else {
        console.warn("没有找到认证token!");
      }
      
      console.log("最终请求URL:", url);
      
      // 显示正在输入指示器
      this.typingIndicator = true;
      
      let assistantMessageText = '';
      let messageAdded = false;
      let lastUpdateTime = 0;
      const updateInterval = 50; // 毫秒，控制更新频率
      
      // 使用EventSource
      this.eventSource = new EventSource(url);
      
      // 添加页面卸载事件监听
      const handleUnload = () => {
        console.log("页面卸载，关闭EventSource连接");
        window.isRefreshing = true;
        this.closeEventSource();
      };
      
      window.addEventListener('beforeunload', handleUnload);
      
      // 处理消息
      this.eventSource.onmessage = (event) => {
        // 检查是否刷新
        if (window.isRefreshing) return;
        
        const content = event.data;
        console.log("收到SSE数据:", content);
                        
        // 处理会话ID - 这应该是第一个收到的消息
        if (content.startsWith('{"conversation_id":')) {
          try {
            const idData = JSON.parse(content);
            if (idData.conversation_id) {
              console.log(`收到会话ID: ${idData.conversation_id}`);
              
              // 通过路由判断是否是新对话
              const isNewChatRoute = this.isNewChat();
              
              // 详细记录当前状态
              console.log("收到ID时的路由状态:", {
                "接收到的ID": idData.conversation_id,
                "当前路由": this.$route.path,
                "isNewChat(路由判断)": isNewChatRoute
              });
              
              // 只对新对话更新状态和URL
              if (isNewChatRoute) {
                console.log("处理新对话ID：路由=/chat/c，更新聊天对象和URL");
                
                // 创建历史记录的深拷贝
                const newChatHistory = [...this.chatHistory];
                
                // 确保索引有效
                if (this.currentChatIndex >= 0 && this.currentChatIndex < newChatHistory.length) {
                  // 完全替换对象，避免引用问题
                  const updatedChat = {
                    ...newChatHistory[this.currentChatIndex],
                    id: idData.conversation_id
                  };
                  
                  newChatHistory[this.currentChatIndex] = updatedChat;
                  this.chatHistory = newChatHistory;
                  
                  // 更新当前会话ID
                  this.currentConversationId = idData.conversation_id;
                  console.log("已将当前聊天ID更新为:", idData.conversation_id);
                  
                  // 更新URL
                  console.log("更新URL为:", `/chat/c/${idData.conversation_id}`);
                  this.$router.push({
                    name: 'ChatConversation',
                    params: { id: idData.conversation_id.toString() },
                    replace: true
                  }).catch(err => {
                    if (err.name !== 'NavigationDuplicated') {
                      console.error("更新URL失败:", err);
                    }
                  });
                } else {
                  console.error("无效的当前聊天索引:", this.currentChatIndex);
                }
              } else {
                console.log("这不是新对话(路由已有ID)，使用现有ID继续对话");
              }
            }
          } catch (e) {
            console.error('解析会话ID失败:', e);
          }
          return;
        }
                        
        // 处理完成信号
        if (content === '[DONE]') {
          this.typingIndicator = false;
          
          // 正常完成，清除状态
          this.activeConversationId = null;
          
          // 关闭EventSource
          this.closeEventSource();
          
          // 移除页面卸载事件监听
          window.removeEventListener('beforeunload', handleUnload);
          
          // 最终更新UI
          this.finalizeMessageUpdate(assistantMessageText);
          return;
        }
                        
        // 处理错误
        if (content.startsWith('⚠️')) {
          if (!messageAdded) {
            this.typingIndicator = false;
            this.addErrorMessage(content);
            messageAdded = true;
          } else {
            // 更新错误消息
            assistantMessageText += "\n" + content;
            // 直接更新DOM
            this.updateMessageDOM(assistantMessageText);
          }
          return;
        }
                        
        // 处理普通内容
        if (!messageAdded) {
          this.typingIndicator = false;
          this.addEmptyReceivedMessage();
          messageAdded = true;
        }
                        
        // 将新内容附加到消息文本
        assistantMessageText += content;
        
        // 限制更新频率，避免过多的响应式更新
        const now = Date.now();
        if (now - lastUpdateTime > updateInterval || content.includes('\n')) {
          // 直接更新DOM
          this.updateMessageDOM(assistantMessageText);
          lastUpdateTime = now;
        }
      };
      
      // 处理错误
      this.eventSource.onerror = (error) => {
        console.error('EventSource错误:', error);
        
        // 尝试重连
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnectAttempts++;
          console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
          
          // 不关闭EventSource，让其自动尝试重连
          return;
        }
        
        // 超过最大重连次数，关闭连接
        this.closeEventSource();
        
        // 显示错误消息
        this.typingIndicator = false;
        if (!messageAdded) {
          this.addErrorMessage('连接中断，请稍后重试');
        } else {
          assistantMessageText += "\n\n[连接中断，请稍后重试]";
          this.updateMessageDOM(assistantMessageText);
          // 最终更新响应式数据
          this.finalizeMessageUpdate(assistantMessageText);
        }
        
        // 移除页面卸载事件监听
        window.removeEventListener('beforeunload', handleUnload);
      };
      
      // 处理连接打开
      this.eventSource.onopen = () => {
        console.log('EventSource连接已打开');
        // 重置重连计数
        this.reconnectAttempts = 0;
      };
    },
    watch: {
      // 监听currentChat.messages的变化，自动滚动到底部
      'currentChat.messages': {
        handler(newMessages, oldMessages) {
          // 如果消息数量增加，滚动到底部
          if (!oldMessages || newMessages.length > oldMessages.length) {
            this.scrollToBottom(true);
          }
        },
        deep: true
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 20px;
  font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif;
}

.chat-wrapper {
  width: 100%;
  max-width: 1200px;
  height: calc(100vh - 140px);
  border-radius: 15px;
  overflow: hidden;
  display: flex;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(67, 97, 238, 0.1);
  background: #fff;
}

.chat-sidebar {
  width: 300px;
  background: #f9f9f9;
  border-right: 1px solid rgba(67, 97, 238, 0.1);
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 20px 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(67, 97, 238, 0.08);
  background-color: rgba(249, 250, 255, 0.8);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  position: sticky;
  top: 0;
  z-index: 10;
}

.history-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.new-chat-btn {
  padding: 10px 15px;
  background: linear-gradient(135deg, #4361ee, #3a0ca3);
  color: white;
  border: none;
  border-radius: 30px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  box-shadow: 0 3px 10px rgba(67, 97, 238, 0.2);
}

.new-chat-btn:hover {
  background: linear-gradient(135deg, #3a56e8, #3407a1);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(67, 97, 238, 0.25);
}

.new-chat-btn span {
  margin-right: 5px;
  font-size: 16px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  padding: 15px;
  background-color: #ffffff;
  border-radius: 10px;
  border: 1px solid rgba(67, 97, 238, 0.1);
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.history-item:hover {
  background-color: #f5f7ff;
  border-color: rgba(67, 97, 238, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.history-item.active {
  background: #f0f4ff;
  border-left: 3px solid #4361ee;
  box-shadow: 0 3px 15px rgba(67, 97, 238, 0.1);
}

.history-title {
  font-weight: 500;
  margin-bottom: 5px;
  color: #333;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #777;
}

.empty-history {
  color: #777;
  text-align: center;
  margin-top: 50px;
  font-size: 14px;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-header {
  padding: 20px 25px;
  background-color: rgba(249, 250, 255, 0.8);
  border-bottom: 1px solid rgba(67, 97, 238, 0.08);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.chat-header-actions {
  display: flex;
  gap: 15px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  background-color: #ffffff;
}

.message {
  display: flex;
  flex-direction: column;
  position: relative;
}

.message.sent {
  align-self: flex-end;
  max-width: 70%;
}

.message.received {
  align-self: flex-start;
  max-width: 60%;
}

.message-content {
  padding: 16px 20px;
  border-radius: 16px;
  font-size: 15px;
  line-height: 1.6;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message.sent .message-content {
  background: linear-gradient(135deg, #4361ee, #3a0ca3);
  color: white;
  border-top-right-radius: 0;
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.15);
}

.message.received .message-content {
  background: #f5f7fa;
  color: #333;
  border-top-left-radius: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  align-self: flex-end;
  margin-right: 5px;
}

.message.sent .message-time {
  margin-right: 5px;
}

.message.received .message-time {
  margin-left: 5px;
}

/* Markdown styles inside message */
.message.received .message-content a {
  color: #4361ee;
  text-decoration: none;
  border-bottom: 1px solid rgba(67, 97, 238, 0.3);
  transition: all 0.2s;
  padding-bottom: 1px;
}

.message.received .message-content a:hover {
  border-color: #4361ee;
  background-color: rgba(67, 97, 238, 0.05);
}

.message.received .message-content pre {
  background-color: #f0f2f5;
  border-radius: 8px;
  padding: 16px;
  overflow-x: auto;
  margin: 12px 0;
  font-family: 'Roboto Mono', 'Menlo', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  border: 1px solid #e4e7ed;
}

.message.received .message-content code {
  background-color: rgba(67, 97, 238, 0.08);
  padding: 3px 6px;
  border-radius: 4px;
  font-family: 'Roboto Mono', 'Menlo', 'Courier New', monospace;
  font-size: 0.9em;
  color: #3a0ca3;
}

.message.received .message-content pre code {
  background-color: transparent;
  padding: 0;
  color: inherit;
}

.message.received .message-content ul, 
.message.received .message-content ol {
  margin: 10px 0;
  padding-left: 24px;
}

.message.received .message-content li {
  margin-bottom: 6px;
}

.message.received .message-content h1,
.message.received .message-content h2,
.message.received .message-content h3,
.message.received .message-content h4 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: 600;
}

.message.received .message-content p {
  margin: 12px 0;
  line-height: 1.7;
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: #f3f4f6;
  border-radius: 15px;
  border-top-left-radius: 0;
  width: fit-content;
  align-self: flex-start;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background: #888;
  display: block;
  border-radius: 50%;
  margin: 0 2px;
  opacity: 0.4;
  animation: blink 1.3s linear infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes blink {
  50% {
    opacity: 1;
  }
}

.input-area {
  display: flex;
  padding: 20px 25px;
  background-color: rgba(249, 250, 255, 0.8);
  border-top: 1px solid rgba(67, 97, 238, 0.08);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  position: relative;
}

.message-input {
  flex: 1;
  padding: 15px 20px;
  border: 1px solid rgba(67, 97, 238, 0.1);
  border-radius: 30px;
  font-size: 15px;
  outline: none;
  transition: all 0.3s;
  background: white;
  color: #333333;
  box-shadow: 0 2px 10px rgba(67, 97, 238, 0.05);
}

.message-input:focus {
  border-color: #4361ee;
  box-shadow: 0 3px 15px rgba(67, 97, 238, 0.1);
  transform: translateY(-1px);
}

.send-button {
  margin-left: 12px;
  padding: 0 25px;
  background: linear-gradient(135deg, #4361ee, #3a0ca3);
  color: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 3px 10px rgba(67, 97, 238, 0.2);
  position: relative;
  overflow: hidden;
}

.send-button:hover {
  background: linear-gradient(135deg, #3a56e8, #3407a1);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(67, 97, 238, 0.25);
}

.send-button:active {
  transform: translateY(0);
}

.send-button::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1, 1) translate(-50%);
  transform-origin: 50% 50%;
}

.send-button:focus:not(:active)::after {
  animation: ripple 1s ease-out;
}

@keyframes ripple {
  0% {
    transform: scale(0, 0);
    opacity: 0.5;
  }
  20% {
    transform: scale(25, 25);
    opacity: 0.3;
  }
  100% {
    opacity: 0;
    transform: scale(40, 40);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-wrapper {
    flex-direction: column;
    height: calc(100vh - 140px);
  }
  
  .chat-sidebar {
    width: 100%;
    height: 35%;
    border-right: none;
    border-bottom: 1px solid rgba(67, 97, 238, 0.1);
  }
  
  .chat-main {
    height: 65%;
  }
  
  .history-header, .chat-header {
    padding: 15px;
  }
  
  .messages {
    padding: 15px;
  }
  
  .input-area {
    padding: 15px;
  }
  
  .message-input {
    padding: 12px 15px;
  }
  
  .send-button {
    padding: 0 15px;
  }
}

.dark-theme {
  color-scheme: dark;
}

.dark-theme .chat-container {
  color: #e0e0e0;
}

.dark-theme .chat-wrapper {
  background: #121212;
  border: 1px solid #2a2a35;
  box-shadow: 0 5px 30px rgba(0, 0, 0, 0.3);
}

.dark-theme .chat-sidebar {
  background: #1a1a1a;
  border-right: 1px solid #2a2a35;
}

.dark-theme .history-header {
  background: rgba(26, 26, 26, 0.95);
  border-bottom: 1px solid #2a2a35;
}

.dark-theme .history-header h3 {
  color: #e0e0e0;
}

.dark-theme .new-chat-btn {
  background: linear-gradient(135deg, #818cf8, #4338ca);
  box-shadow: 0 3px 10px rgba(129, 140, 248, 0.2);
}

.dark-theme .new-chat-btn:hover {
  background: linear-gradient(135deg, #717cf8, #3338ca);
  box-shadow: 0 5px 15px rgba(129, 140, 248, 0.3);
}

.dark-theme .history-item {
  background-color: #252530;
  border: 1px solid #2a2a35;
}

.dark-theme .history-item:hover {
  background-color: #2a2a35;
  border-color: #3a3a45;
}

.dark-theme .history-item.active {
  background: #2a2a35;
  border-left: 3px solid #818cf8;
  box-shadow: 0 3px 15px rgba(129, 140, 248, 0.1);
}

.dark-theme .history-title {
  color: #e0e0e0;
}

.dark-theme .history-info {
  color: #aaaaaa;
}

.dark-theme .empty-history {
  color: #aaaaaa;
}

.dark-theme .chat-header {
  background: rgba(26, 26, 26, 0.95);
  border-bottom: 1px solid #2a2a35;
}

.dark-theme .chat-header h2 {
  color: #e0e0e0;
}

.dark-theme .messages {
  background: #121212;
}

.dark-theme .message.sent .message-content {
  background: linear-gradient(135deg, #818cf8, #4338ca);
}

.dark-theme .message.received .message-content {
  background: #252530;
  color: #e0e0e0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dark-theme .message-time {
  color: #777;
}

.dark-theme .typing-indicator {
  background: #252530;
}

.dark-theme .typing-indicator span {
  background: #aaa;
}

.dark-theme .input-area {
  background: rgba(26, 26, 26, 0.95);
  border-top: 1px solid #2a2a35;
}

.dark-theme .message-input {
  background: #252530;
  color: #e0e0e0;
  border: 1px solid #2a2a35;
}

.dark-theme .message-input:focus {
  border-color: #818cf8;
  box-shadow: 0 3px 15px rgba(129, 140, 248, 0.1);
}

.dark-theme .send-button {
  background: linear-gradient(135deg, #818cf8, #4338ca);
  box-shadow: 0 3px 10px rgba(129, 140, 248, 0.2);
}

.dark-theme .send-button:hover {
  background: linear-gradient(135deg, #717cf8, #3338ca);
  box-shadow: 0 5px 15px rgba(129, 140, 248, 0.3);
}

.dark-theme .message.received .message-content a {
  color: #818cf8;
}

.dark-theme .message.received .message-content pre {
  background-color: #1e1e2d;
  border: 1px solid #2a2a35;
}

.dark-theme .message.received .message-content code {
  background-color: rgba(129, 140, 248, 0.1);
}

.help-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4361ee, #3a0ca3);
  color: white;
  border: none;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.help-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
}

.dark-theme .help-button {
  background: linear-gradient(135deg, #818cf8, #4338ca);
  box-shadow: 0 4px 15px rgba(129, 140, 248, 0.3);
}

.dark-theme .help-button:hover {
  box-shadow: 0 6px 20px rgba(129, 140, 248, 0.4);
}

.new-chat-label {
  display: inline-block;
  color: #4361ee;
  font-weight: 600;
  border: 1px solid #4361ee;
  border-radius: 4px;
  padding: 1px 6px;
  font-size: 12px;
  background-color: rgba(67, 97, 238, 0.1);
}

.dark-theme .new-chat-label {
  color: #818cf8;
  border-color: #818cf8;
  background-color: rgba(129, 140, 248, 0.1);
}

/* 引导功能样式 */
.guide-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 100000;
  display: flex;
  justify-content: center;
  align-items: center;
  animation: fadeIn 0.3s ease;
}

.guide-container {
  width: 550px;
  max-width: 90%;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 30px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  animation: slideIn 0.4s ease;
  position: relative;
}

.dark-theme .guide-container {
  background-color: #252530;
  border: 1px solid #3a3a45;
}

.guide-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 24px;
  border-bottom: 1px solid #eaeaea;
  background-color: #f8f9fa;
}

.dark-theme .guide-header {
  background-color: #1e1e24;
  border-bottom: 1px solid #3a3a45;
}

.guide-header h3 {
  font-size: 18px;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  font-weight: 600;
}

.dark-theme .guide-header h3 {
  color: #e0e0e0;
}

.guide-header h3 span {
  font-size: 14px;
  color: #6b7280;
  background-color: #e5e7eb;
  border-radius: 20px;
  padding: 2px 10px;
  margin-left: 10px;
  font-weight: 500;
}

.dark-theme .guide-header h3 span {
  background-color: #3a3a45;
  color: #d1d5db;
}

.guide-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #6b7280;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.guide-close:hover {
  background-color: #f3f4f6;
  color: #4b5563;
}

.dark-theme .guide-close {
  color: #d1d5db;
}

.dark-theme .guide-close:hover {
  background-color: #3a3a45;
  color: #ffffff;
}

.guide-content {
  padding: 36px 24px;
  min-height: 250px;
}

.guide-step {
  text-align: center;
  animation: fadeInUp 0.4s ease;
}

.guide-icon {
  font-size: 54px;
  color: #4361ee;
  margin-bottom: 22px;
  animation: bounce 1s ease infinite alternate;
}

.dark-theme .guide-icon {
  color: #818cf8;
}

.guide-step h4 {
  font-size: 20px;
  color: #333;
  margin-bottom: 16px;
  position: relative;
  display: inline-block;
}

.dark-theme .guide-step h4 {
  color: #e0e0e0;
}

.guide-step h4:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background: #4361ee;
  bottom: -5px;
  left: 0;
  transform: scaleX(0);
  transform-origin: left;
  animation: lineGrow 0.5s 0.2s forwards;
}

.dark-theme .guide-step h4:after {
  background: #818cf8;
}

.guide-step p {
  font-size: 16px;
  color: #6b7280;
  line-height: 1.6;
  max-width: 90%;
  margin: 0 auto;
}

.dark-theme .guide-step p {
  color: #aaaaaa;
}

.guide-footer {
  border-top: 1px solid #eaeaea;
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dark-theme .guide-footer {
  border-top: 1px solid #3a3a45;
}

.guide-footer .btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.guide-footer .btn.primary {
  background-color: #4361ee;
  color: white;
}

.guide-footer .btn.secondary {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #e5e7eb;
}

.dark-theme .guide-footer .btn.primary {
  background-color: #818cf8;
}

.dark-theme .guide-footer .btn.secondary {
  background-color: #252530;
  color: #e0e0e0;
  border: 1px solid #3a3a45;
}

/* 引导功能的动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes fadeInUp {
  from { transform: translateY(10px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes bounce {
  from { transform: translateY(0); }
  to { transform: translateY(-10px); }
}

@keyframes lineGrow {
  from { transform: scaleX(0); }
  to { transform: scaleX(1); }
}

/* 高亮样式 */
.highlight-sidebar {
  box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.5);
  position: relative;
  z-index: 10;
}

.highlight-input {
  box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.5);
  position: relative;
  z-index: 10;
}

.highlight-chat {
  box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.5);
  position: relative;
  z-index: 10;
}

.highlight-history {
  box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.5);
  position: relative;
  z-index: 10;
}
</style> 